package com.aichat.ai_chatbackend.config;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;

import static cn.dev33.satoken.SaManager.log;

@Configuration
public class ChatConfig {

    @Bean
    ChatClient chatClient(ChatClient.Builder builder) {
        return builder.defaultSystem("你是一个陪聊助手，请耐心的听用户的倾诉并给出温暖的回应")
                .build();
    }

    @Bean
    @Primary
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder
                // 使用新的连接超时API
                .connectTimeout(Duration.ofSeconds(2))
                // 使用新的读取超时API
                .readTimeout(Duration.ofSeconds(10))
                // 添加拦截器记录请求时间
                .interceptors((request, body, execution) -> {
                    long startTime = System.currentTimeMillis();
                    ClientHttpResponse response = execution.execute(request, body);
                    long endTime = System.currentTimeMillis();
                    log.info("HTTP请求 {} 耗时: {}ms", request.getURI(), endTime - startTime);
                    return response;
                })
                .build();
    }
}
